package top.lishuoboy.jdbc.a4blob;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.io.unit.DataSizeUtil;
import lombok.extern.slf4j.Slf4j;
import top.lishuoboy.jdbc.a2conn.JDBCUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


/**
 * @author lishuoboy
 * @date 2021-12-19 19:18
 */
@Slf4j
public class A4BlobCurd {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // 创建连接
            conn = JDBCUtil.getConn();
            // 清表
            conn.createStatement().executeUpdate("truncate blob_test");

            // 1、新增
            String sSql = "insert into blob_test (id, photo) values (?, ?)";
            ps = conn.prepareStatement(sSql);
            ps.setInt(1, 1);
            InputStream is = ResourceUtil.getStream("top/lishuoboy/jdbc/a4blob/blob_test.png");
            ps.setBlob(2, is);
            log.debug("ps:" + ps);
            int successCount3 = ps.executeUpdate();
            log.debug("successCount:" + successCount3);

            // 2、查询
            sSql = "select * from blob_test where id = ?";
            ps = conn.prepareStatement(sSql);
            ps.setString(1, "1");
            log.debug("ps:" + ps);
            rs = ps.executeQuery();
            while (rs.next()) {
                Blob photo = rs.getBlob("photo");
                System.out.println(DataSizeUtil.format(photo.length()));
                IoUtil.copy(photo.getBinaryStream(), new FileOutputStream(FileUtil.touch(new File("tmp/blob_test_copy.png"))));
            }

        } catch (Exception e) {
            log.error("异常", e);
        } finally {
            JDBCUtil.close(rs, ps, conn);
        }
    }
}
